//iframe.html
var currentSourcePage, currentPapaElement, currentField, currentSelectField;

var getSourcePageTable = function(){
	currentSourcePage = null;
	var html = [];
	html.push('<div class="papa-content">');
	//tbar
	html.push('<div class="papa-bar"><button type="button" id="papa-sp-add" class="btn btn-default">新增数据页</button></div>')
	if(sourcePages && sourcePages.length){
		html.push('<table class="table"  id="sourcepage-table">');
		html.push('<tr><th>#</th><th>名称</th><th width="50%">URL</th><th>行选择器</th><th>操作</th></tr>')
		for (var i = 0; i < sourcePages.length; i++) {
			html.push('<tr>');
			var p = sourcePages[i];
			html.push('<td>'+(i + 1)+'</td>');
			html.push('<td>'+p.id+'</td>');
			html.push('<td>'+p.name+'</td>');
			html.push('<td>'+p.url+'</td>');
			html.push('<td>'+p.rowElement+'</td>');
			html.push('<td>');
			html.push('<button class="btn btn-default btn-xs papa-sp-edit">编辑</button>');
			html = html.concat(getDeleteAction());
			html.push('<button class="btn btn-default btn-xs papa-page">分页策略</button>');
			html.push('<button class="btn btn-default btn-xs papa-fields">字段</button>');
			html.push('<button class="btn btn-default btn-xs papa-links">链接页面</button>');
			html.push('</td>');
			html.push('</tr>');
		}
		html.push('</table>');
	}
	html.push('</div>');
	return html.join('');
}

var getSourcePageForm = function(){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-sp-name" class="col-sm-2 control-label">ID</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-sp-id" value="'+(currentSourcePage ? currentSourcePage.id : '')+'">');
	html.push('</div>');
	html.push('</div>');
	html.push('<div class="form-group">');
	html.push('<label for="papa-sp-name" class="col-sm-2 control-label">名称</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-sp-name" value="'+(currentSourcePage ? currentSourcePage.name : '')+'">');
	html.push('</div>');
	html.push('</div>');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-sp-url" class="col-sm-2 control-label">地址(URL)</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-sp-url" value="'+(currentSourcePage ? currentSourcePage.url : '')+'">');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSelectComponent({fieldId: 'papa-sp-rowElement'}));
	html = html.concat(getSaveAndCancel('sp'));
	
	html.push('</div>');
	return html.join('');
}

var getPagingForm = function(){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-paging-mode" class="col-sm-2 control-label">动作类型</label>');
	html.push('<div class="col-sm-3">');
	html.push('<select id="papa-paging-mode" class="form-control"><option value="url">a标签(href)</option><option value="scroll">滚动条(Ajax)</option><option value="click">单击(Ajax)</option></select>');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSelectComponent({
		fieldId: 'papa-paging-element',
		fieldLabel: '下页选择器'
	}));
	
	html = html.concat(getSaveAndCancel('paging'));
	
	html.push('</div>');
	return html.join('');
}

var getLinkForm = function(){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-link-sp" class="col-sm-2 control-label">数据页</label>');
	html.push('<div class="col-sm-3">');
	html.push('<select id="papa-link-sp" class="form-control">');
	html.push('<option value="-1">选择数据页</option>');
	for (var i = 0; i < sourcePages.length; i++) {
		var p = sourcePages[i];
		if(p != currentSourcePage){
			html.push('<option value="'+(i)+'">'+p.name+'</option>');
		}
	}
	html.push('</select>');
	html.push('</div>');
	html.push('</div>');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-link-mode" class="col-sm-2 control-label">动作类型</label>');
	html.push('<div class="col-sm-3">');
	html.push('<select id="papa-link-mode" class="form-control"><option value="url">a标签(href)</option><option value="scroll">滚动条(Ajax)</option><option value="click">单击(Ajax)</option></select>');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSelectComponent({
		fieldId: 'papa-link-element',
		fieldLabel: '跳转页选择器'
	}));
	
	html = html.concat(getSaveAndCancel('link'));
	
	html.push('</div>');
	return html.join('');
}

var getFieldTable = function(){
	currentField = null;
	var html = [];
	html.push('<div class="papa-content">');
	//tbar
	html.push('<div class="papa-bar"><button type="button" id="papa-field-add" class="btn btn-default">新增字段</button>&nbsp;&nbsp;<button type="button" id="papa-field-topage" class="btn btn-default">返回数据页</button></div>')
	if(currentSourcePage && currentSourcePage.fields){
		html.push('<table class="table" id="field-table">');
		html.push('<tr><th>#</th><th>字段ID</th><th>字段名称</th><th>选择器</th><th>提取方式</th><th>操作</th></tr>')
		for (var i = 0; i < currentSourcePage.fields.length; i++) {
			html.push('<tr>');
			var f = currentSourcePage.fields[i];
			html.push('<td>'+(i + 1)+'</td>');
			html.push('<td>'+f.id+'</td>');
			html.push('<td>'+f.title+'</td>');
			html.push('<td>'+f.element+'</td>');
			html.push('<td>'+f.contentExtractor+'</td>');
			html.push('<td>');
			html.push('<button class="btn btn-default btn-xs papa-field-edit">编辑</button>');
			html = html.concat(getDeleteAction());
			html.push('</td>');
			html.push('</tr>');
		}
		html.push('</table>');
	}
	html.push('</div>');
	return html.join('');
}

var getFieldForm = function(){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-field-id" class="col-sm-2 control-label">字段ID</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-field-id" value="'+(currentField ? currentField.id : '')+'">');
	html.push('</div>');
	html.push('</div>');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-field-name" class="col-sm-2 control-label">字段名称</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-field-name" value="'+(currentField ? currentField.title : '')+'">');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSelectComponent({fieldId: 'papa-field-element', fieldLabel: '字段选择器'}));
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-field-extractor" class="col-sm-2 control-label">提取方式</label>');
	html.push('<div class="col-sm-2">');
	html.push('<select class="form-control" id="papa-field-extractor"><option value="text">提取文本</option><option value="attr">提取属性</option></select>');
	html.push('</div>');
	html.push('<div class="col-sm-2">');
	html.push('<input type="text" class="form-control" placeholder="属性名">');
	html.push('<input type="text" class="form-control" placeholder="元素表达式">');
	html.push('</div>');
	html.push('<div class="col-sm-5">');
	html.push('<input type="text" class="form-control" placeholder="字符串表达式">');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSaveAndCancel('field'));
	
	html.push('</div>');
	return html.join('');
}


var getSelectorTable = function(){
	currentPapaElement = null;
	var html = [];
	html.push('<div class="papa-content">');
	//tbar
	html.push('<div class="papa-bar"><button type="button" id="papa-sel-add" class="btn btn-default">新增选择器</button></div>')
	if(papaElements && papaElements.length){
		html.push('<table class="table"  id="selector-table">');
		html.push('<tr><th>#</th><th>名称</th><th>选择器</th><th>父选择器</th><th>操作</th></tr>')
		for (var i = 0; i < papaElements.length; i++) {
			html.push('<tr>');
			var p = papaElements[i];
			html.push('<td>'+(i + 1)+'</td>');
			html.push('<td>'+p.name+'</td>');
			html.push('<td>'+p.selector+'</td>');
			html.push('<td>'+(p.parentElement || '')+'</td>');
			html.push('<td>');
			html.push('<button class="btn btn-default btn-xs papa-sel-edit">编辑</button>');
			html = html.concat(getDeleteAction());
			html.push('</td>');
			html.push('</tr>');
		}
		html.push('</table>');
	}
	html.push('</div>');
	return html.join('');
}

var getSelectorForm = function(){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html.push('<div class="form-group">');
	html.push('<label for="papa-sel-name" class="col-sm-2 control-label">名称</label>');
	html.push('<div class="col-sm-9">');
	html.push('<input type="text" class="form-control" id="papa-sel-name" value="'+(currentPapaElement ? currentPapaElement.name : '')+'">');
	html.push('</div>');
	html.push('</div>');
	
	html = html.concat(getSelectComponent({fieldId: 'papa-sel-element'}));
	html = html.concat(getSaveAndCancel('sel'));
	
	html.push('</div>');
	return html.join('');
}

var getSaveAndCancel = function(scope){
	var html = [];
	html.push('<div class="form-group">');
	html.push('<div class="col-sm-offset-2 col-sm-10">');
	html.push('<button class="papa-cancel btn btn-default">取消</button>&nbsp;&nbsp;');
	html.push('<button id="papa-'+scope+'-save" class="btn btn-default">保存</button>');
	html.push('</div>');
	html.push('</div>');
	return html;
}

var getSelectComponent = function(_config){
	var html = [];
	html.push('<div class="form-group">');
	html.push('<label for="'+_config.fieldId+'" class="col-sm-2 control-label">'+(_config.fieldLabel || '行选择器')+'</label>');
	html.push('<div class="col-sm-2">');
	html.push('<select '+(_config.disableParent ? disabled="disabled" : "")+' class="form-control"><option value="-1">父选择器</option>');
	for (var i = 0; i < papaElements.length; i++) {
		var e = papaElements[i];
		if(e != currentPapaElement){
			html.push('<option value="'+i+'">'+e.name+'</option>')
		}
	}
	html.push('</select>');
	html.push('</div>');
	html.push('<div class="col-sm-5">');
	html.push('<input type="text" class="form-control select-field" id="'+(_config.fieldId || '')+'">');
	html.push('</div>');
	html.push('<div class="btn-group" style="margin-left: -17px;">');
	html.push('<button class="btn btn-default papa-selector-btn">手动选取</button>');
	if(_config.canSelect){
		html.push('<div class="btn-group">');
		html.push('<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">从列表中选择<span class="caret"></span></button>');
		html.push('<ul class="dropdown-menu">');
		for (var i = 0; i < papaElements.length; i++) {
			var e = papaElements[i];
			html.push('<li><a href="#" onclick="_selectSelector('+i+')">'+e.name+'</a></li>');
		}
		html.push('</ul>');
		html.push('</div>');
	}
	if(_config.needHelp){
		html.push('<button class="btn btn-default papa-helpselect-btn">教我选择</button>');
	}
	html.push('</div>');
	html.push('</div>');
	return html;
}

var getHelpSelectCompnent = function(mode){
	var html = [];
	html.push('<div class="papa-content form-horizontal">');
	
	html = html.concat(getSelectComponent({
		fieldId: 'papa-help-current',
		fieldLabel: '当前页',
		disableParent: true
	}));
	html = html.concat(getSelectComponent({
		fieldId: 'papa-help-next',
		fieldLabel: '下一页',
		disableParent: true
	}));
	
	html.push('<label for="papa-help-result" class="col-sm-2 control-label">计算结果</label>');
	html.push('<div class="col-sm-7">');
	html.push('<input type="text" class="form-control" id="papa-help-result" value="'+(currentPapaElement ? currentPapaElement.name : '')+'">');
	html.push('</div>');
	html.push('<div class="col-sm-2">');
	html.push('<button class="btn btn-default papa-help-cal">计算</button>');
	html.push('</div>');
	
	html.push('</div>');
	return html.join('');
}

var getDeleteAction = function(){
	var html = [];
	html.push('<div class="btn-group">');
	html.push('<button class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">删除</button>');
	html.push('<ul class="dropdown-menu">');
	html.push('<li><a href="#" class="papa-del">确认</a></li>');
	html.push('<li><a href="#">取消</a></li>');
	html.push('</ul>');
	html.push('</div>');
	return html;
}

var initUIAndEvent = function(){
	$('body')
		.on('click', '#sitemap_download', function(){
			var blob = JSON.stringify(sitemap2db());
			$('#sitemap_textarea').val(blob);
		})
		.on('click', '#sitemap_upload', function(){
			var blob = $('#sitemap_textarea').val();
			if(blob){
				db2sitemap(JSON.parse(blob));
				_write();
				$('#papa-tab-datasource').html(getSourcePageTable());
				$('#papa-tab-selectors').html(getSelectorTable());
			}
		})
		.on('click', '#sitemap_start', function(){
			chrome.runtime.sendMessage({
				cmd: 'startScrape',
				params: sitemap2db()
			});
		})
		.on('click', '.papa-selector-btn', function(){
			var textfield = $(this).parent().prev().children();
			currentSelectField = textfield;
			chrome.runtime.sendMessage({
				cmd: 'startSelect',
				params: {
					multi: 0
				}
			});
		})
		.on('click', '.papa-del', function(){
			var id = $(this).parents('table')[0].id;
			var i = _getRowId($(this));
			if(id == 'selector-table'){
				papaElements.splice(i , 1);
				$('#papa-tab-selectors').html(getSelectorTable());
			}
			else if(id == 'sourcepage-table'){
				sourcePages.splice(i , 1);
				$('#papa-tab-datasource').html(getSourcePageTable());
			}
			else if(id == 'field-table'){
				currentSourcePage.fields.splice(i , 1);
				$('#papa-tab-datasource').html(getFieldTable());
			}
			_write();
		})
	
	//数据页
	$('#papa-tab-datasource').html(getSourcePageTable())
		.on('click', '#papa-sp-add', function(){
			$('#papa-tab-datasource').html(getSourcePageForm());
		})
		.on('click', '#papa-sp-save', function(){
			if(currentSourcePage){
				currentSourcePage.id = $('#papa-sp-id').val();
				currentSourcePage.name = $('#papa-sp-name').val();
				currentSourcePage.url = $('#papa-sp-url').val();
				currentSourcePage.rowElement = _getSelector($('#papa-sp-rowElement'))
				currentSourcePage = null;
			}else{
				sourcePages.push($.extend(new SourcePage(),{
					id: $('#papa-sp-id').val(),
					name: $('#papa-sp-name').val(),
					url: $('#papa-sp-url').val(),
					rowElement: _getSelector($('#papa-sp-rowElement'))
				}));
			}
			$('#papa-tab-datasource').html(getSourcePageTable());
			_write();
		})
		.on('click', '.papa-cancel', function(){
			$('#papa-tab-datasource').html(getSourcePageTable());
		})
		.on('click', '.papa-sp-edit', function(){
			var i = _getRowId($(this));
			currentSourcePage = sourcePages[i];
			$('#papa-tab-datasource').html(getSourcePageForm());
			_setSelector(currentSourcePage.rowElement, $('#papa-sp-rowElement'));
		})
		//分页
		.on('click', '.papa-page', function(){
			var i = _getRowId($(this));
			currentSourcePage = sourcePages[i];
			var p = sourcePages[i].paging;
			$('#papa-tab-datasource').html(getPagingForm());
			if(p){
				$('#papa-paging-mode').val(p.type);
				_setSelector(p.nextPageElement, $('#papa-paging-element'));
			}
		})
		.on('click', '#papa-paging-save', function(){
			var p = new Paging();
			p.type = $('#papa-paging-mode').val();
			p.nextPageElement = _getSelector($('#papa-paging-element'))
			currentSourcePage.paging = p;
			$('#papa-tab-datasource').html(getSourcePageTable());
			_write();
		})
		//字段
		.on('click', '.papa-fields', function(){
			var i = _getRowId($(this));
			currentSourcePage = sourcePages[i];
			var p = sourcePages[i].paging;
			$('#papa-tab-datasource').html(getFieldTable());
		})
		.on('click', '#papa-field-topage', function(){
			$('#papa-tab-datasource').html(getSourcePageTable());
		})
		.on('click', '#papa-field-add', function(){
			$('#papa-tab-datasource').html(getFieldForm());
		})
		.on('click', '.papa-field-edit', function(){
			var i = _getRowId($(this));
			currentField = currentSourcePage.fields[i];
			$('#papa-tab-datasource').html(getFieldForm());
			_setExtractor(currentField.contentExtractor, $('#papa-field-extractor'));
			_setSelector(currentField.element, $('#papa-field-element'));
		})
		.on('click', '#papa-field-cancel', function(){
			$('#papa-tab-datasource').html(getFieldTable());
		})
		.on('click', '#papa-field-save', function(){
			if(currentField){
				currentField.id = $('#papa-field-id').val();
				currentField.title = $('#papa-field-name').val();
				currentField.element = _getSelector($('#papa-field-element'));
				currentField.contentExtractor = _getExtractor($('#papa-field-extractor'));
			}else{
				if(!currentSourcePage.fields){
					currentSourcePage.fields = [];
				}
				currentSourcePage.fields.push($.extend(new PapaField(), {
					id: $('#papa-field-id').val(),
					title: $('#papa-field-name').val(),
					element: _getSelector($('#papa-field-element')),
					contentExtractor: _getExtractor($('#papa-field-extractor'))
				}))
			}
			$('#papa-tab-datasource').html(getFieldTable());
			_write();
		})
		//链接页面
		.on('click', '.papa-links', function(){
			var i = _getRowId($(this));
			currentSourcePage = sourcePages[i];
			var l = sourcePages[i].linkedPages[0];
			$('#papa-tab-datasource').html(getLinkForm());
			if(l){
				$('#papa-link-sp').val(sourcePages.indexOf(l.sourcePage));
				$('#papa-link-mode').val(l.paging.type);
				_setSelector(l.paging.nextPageElement, $('#papa-link-element'));
			}
		})
		.on('click', '#papa-link-save', function(){
			var l = currentSourcePage.linkedPages[0] || new LinkedPage();
			var p = l.paging || new Paging();
			p.type = $('#papa-link-mode').val();
			p.nextPageElement = _getSelector($('#papa-link-element'))
			l.paging = p;
			l.sourcePage = sourcePages[parseInt($('#papa-link-sp').val())];
			currentSourcePage.linkedPages[0] = l;
			$('#papa-tab-datasource').html(getSourcePageTable());
			_write();
		})
		
		
	//选择器
	$('#papa-tab-selectors').html(getSelectorTable())
		.on('click', '#papa-sel-add', function(){
			$('#papa-tab-selectors').html(getSelectorForm());
		})
		.on('click', '#papa-sel-save', function(){
			var ele = $.extend(_getSelector($('#papa-sel-element')), {
				name: $('#papa-sel-name').val()
			});
			if(currentPapaElement){
				$.extend(currentPapaElement, ele);
			}else{
				papaElements.push(ele);
			}
			$('#papa-tab-selectors').html(getSelectorTable());
			currentPapaElement = null;
			_write();
		})
		.on('click', '.papa-cancel', function(){
			$('#papa-tab-selectors').html(getSelectorTable());
		})
		.on('click', '.papa-sel-edit', function(){
			var i = _getRowId($(this));
			currentPapaElement = papaElements[i];
			$('#papa-tab-selectors').html(getSelectorForm());
			_setSelector(currentPapaElement, $('#papa-sel-element'));
		})
}

var _getSelector = function(field){
	var parentEle = null;
	var pId = parseInt(field.parent().prev().children().first().val());
	if(pId != -1){
		parentEle = papaElements[pId];
	}
	var e = new PapaElement();
	e.parentElement = parentEle;
	var id = field.attr('data-selector-id');
	if(id){
		var selected = papaElements[id];
		$.extend(e, selected);
	}
	e.selector = field.val();
	return e;
}

var _setSelector = function(e, field){
	if(e.parentElement){
		field.parent().prev().children().first().val(papaElements.indexOf(e.parentElement));
	}
	var id = papaElements.indexOf(e);
	if(id != -1){
		field.attr('data-selector-id', id);
	}
	field.val(e.selector);
}

var _getExtractor = function(selectBox){
	var e = new ContentExtractor();
	e.type = selectBox.val();
	if(e.type == 'attr'){
		e.attr = selectBox.parent().next().children().first().val();
	}
	else if(e.type == 'method'){
		e.attr = selectBox.parent().next().children().last().val();
	}
	e.process = selectBox.parent().next().next().children().first().val();
	return e;
}

var _setExtractor = function(e, selectBox){
	selectBox.val(e.type);
	if(e.type == 'attr'){
		selectBox.parent().next().children().first().val(e.attr).show();
	}
	else if(e.type == 'method'){
		selectBox.parent().next().children().last().val(e.method).show();
	}
	selectBox.parent().next().next().children().first().val(e.process);
}

var _selectSelector = function(i){
	var e = papaElements[i];
	$(this).parentsUntil('.form-group').find('.select-field')
		.text(e.selector)
		.attr('data-selector-id', i);
}

var _getRowId = function(btn){
	return parseInt(btn.parents('tr').children().first().text()) - 1;
}

chrome.runtime.onMessage.addListener(function(msg, _, sendResponse){
	if(msg.cmd == 'endSelect'){
		if(currentSelectField){
			currentSelectField.val(msg.params.selector);
		}
	}
});

var _write = function(){
	var db = {'sitemap': sitemap2db()};
	chrome.storage.local.set(db, function(){
      console.log('Saved sitemap');
    });
}

$(function(){
	chrome.storage.local.get("sitemap", function(db){
		var _sitemap = db["sitemap"];
		db2sitemap(_sitemap);
		
		initUIAndEvent();
		var h = $('body').height();
		var h1 = $('.nav-tabs').height();
		$('.tab-content').height(h - h1 - 6);
	});
	
})

